/*
 * StringUtils.java
 *
 * Created on 2007年5月15日, 下午8:46
 *

 */
package com.focusai.efairy.utils;

import android.text.Editable;
import android.widget.EditText;

import java.io.UnsupportedEncodingException;

/**
 * 字符串处理的辅助方法
 * 
 * @author gzit
 */
public class StringUtils {

	// 安全地截断空白符号
	public static String safeTrim(String src) {
		if (src == null)
			return src;
		return src.trim();

	}

	// 如果字符串为null的话则转化为空
	public static String emptyIfNull(String src) {
		return src == null ? "" : src;
	}

	// 当字符串为Null时，设定默认值
	public static String setValueIfNull(String src, String def) {
		return isBlank(src) ? def : ("null".equals(src) ? null : src);
	}

	// 判断字符串是否为空
	public static boolean isBlank(StringBuffer value) {

		return isBlank(value == null ? null : value.toString());

	}

	// 判断字符串是否为空
	public static boolean isBlank(String value) {
		if (value == null || value.trim().length() == 0) {
			return true;
		}
		return false;
	}

	public static boolean isAllNotBlank(String... values) {
		for (String value : values) {
			if (isBlank(value)) {
				return false;
			}

		}

		return true;

	}

	public static boolean isAllNotStrickBlank(String... values) {

		for (String value : values) {
			if (isStickBlank(value)) {
				return false;
			}

		}

		return true;

	}

	// 查找某个字符串在字符串数组中的位置
	public static int findIndex(String[] items, String item) {
		for (int i = 0; i < items.length; i++) {
			if (items[i].equals(item)) {
				return i;
			}
		}

		return -1;
	}

	public static boolean isStickBlank(String value) {
		if (isBlank(value) || "null".equals(value)) {
			return true;
		}

		return false;

	}

	public static String emptyIfStrickBlank(String value) {
		if (isStickBlank(value)) {
			return "";
		}

		return value;
	}

	public static String emptyIfBlank(String value) {
		if (isBlank(value))
			return "";

		return value;

	}
	//转化文件大小
	public static String getFileSize(String fileSize){
		  String[] arr = {" B"," K", " M", " G"};
		if(fileSize==null||"".endsWith(fileSize)){
			return "0"+arr[0];
		}
		double fileSize_ =0;
		try {
			fileSize_=Double.parseDouble(fileSize);
		} catch (Exception e) {
			return "0"+arr[0];
		}
	    int i = 0;
	    while(fileSize_/1024.0 >= 1.0) {
	    	fileSize_ = fileSize_ /1024.0;
	        i++;
	    }
	    i = i>arr.length ? arr.length : i;
	    if(i==0){
	    	return String.format("%.0f%s",fileSize_,arr[i]);	
	    }
		return String.format("%.2f%s",fileSize_,arr[i]);
	}
	
	/**
	 * 中文校验（字符串全部为中文，返回true）
	 * @return
	 */
	public static boolean checkChinese(String str){
		if(isBlank(str)){
            return  false;
        }
		for (int i = 0; i < str.length(); i++) {
			String subStr = str.substring(i, i+1); 
			boolean cc = java.util.regex.Pattern.matches("[\u4E00-\u9FA5]", subStr); 
			if(!cc){
				return false;
			}
			
		}
		return true;
	}

	/**
	 * 英文校验（字符串全部为英文，返回true）
	 * @return
	 */
	public static boolean isEnglish(String word) {
		word = word.replace(" ","");
		boolean sign = true; // 初始化标志为为'true'
		for (int i = 0; i < word.length(); i++) {
			if (!(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')
					&& !(word.charAt(i) >= 'a' && word.charAt(i) <= 'z')) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 中文校验（字符串全部为中文，返回true）
	 * @return
	 */
	public static boolean containChinese(String str){
		if(isBlank(str)){
			return  false;
		}
		for (int i = 0; i < str.length(); i++) {
			String subStr = str.substring(i, i+1);
			boolean cc = java.util.regex.Pattern.matches("[\u4E00-\u9FA5]", subStr);
			if(cc){
				return true;
			}

		}
		return false;
	}

	/**
	 * 返回字符串长度，中文根据编码方式的不同可能占多个字节（默认用UTF-8编码）
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static int getByteLength(String str ) {
		return getByteLength(str, "UTF-8");
	}
	
	/**
	 *  返回字符串长度，中文根据编码方式的不同可能占多个字节
	 * @param str
	 * @param code
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static int getByteLength(String str , String code)  {
		try {
			return str.getBytes("UTF-8").length;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 *
	 * @param msg 消息体长度如果有多个空格时只能以一个空格结尾
	 * @return
	 */
	public static String doCheckLast(String msg) {
		if(null == msg || msg.length()<2){
			return msg;
		}else{
			return msg.replaceAll("\\s\\s+$", " ");
		}
	}


    public static String dossId(String ssid){
        if(isBlank(ssid)){
            return "";
        }
        String newssid=ssid;
        if(ssid.startsWith("\"")&&ssid.endsWith("\"")){
            newssid= ssid.substring(1,ssid.length()-1);
        }
        return newssid;
    }

	public static boolean isHttpUrl(String url){
		if(isStickBlank(url)){
			return false;
		}else{
			if(url.startsWith("http:") || url.startsWith("https:") || url.startsWith("HTTP:") || url.startsWith("HTTPS:")){
				return true;
			}
		}
		return false;
	}

	public static boolean isNetUri(String url){
		if(isStickBlank(url)){
			return false;
		}else{
			if(url.startsWith("http:") || url.startsWith("https:")
					|| url.startsWith("HTTP:") || url.startsWith("HTTPS:")
					|| url.startsWith("ftp:") || url.startsWith("FTP:")){
				return true;
			}
		}
		return false;
	}
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
			return true;
		}
		return false;
	}
	public static final char SEPARATOR = '-';
	public static final int FIRST_SEPARATOR_POSITION = 3;
	public static final int SECOND_SEPARATOR_POSITION = 7;
	/*
     * -1. Invalid.
     *
     * 0. Formatted.
     *
     * 1. Not formatted cause one index at least is a separator, except index 3
     * and index 7.
     *
     * 2. Not formatted cause index 3 isn't a separator.
     *
     * 3. Not formatted cause index 7 isn't a separator.
     *
     * 4. Not formatted cause has a separator in the tail.
     */
	public static int parsePhoneNumber(String phoneNumber) {
		if (phoneNumber == null) {
			return -1;
		}

		if (getOneInvalidSeparatorIndex(phoneNumber) != -1) {//除index = 3和8是“-”以外，其他位置有“-”时，按1处理
			return 1;
		}

		if ((phoneNumber.length() > FIRST_SEPARATOR_POSITION)//字符数超3个，同时index=3的字符不是“-”，则按2来处理
				&& (phoneNumber.charAt(FIRST_SEPARATOR_POSITION) != SEPARATOR)) {
			return 2;
		}
		if ((phoneNumber.length() > (SECOND_SEPARATOR_POSITION + 1))//字符数超8个，同时index=8的字符不是“-”，则按3来处理
				&& (phoneNumber.charAt(SECOND_SEPARATOR_POSITION + 1) != SEPARATOR)) {
			return 3;
		}

		if ((phoneNumber.length() == (FIRST_SEPARATOR_POSITION + 1))
				|| (phoneNumber.length() == (SECOND_SEPARATOR_POSITION + 1 + 1))) {
			return 4;
		}
		if(phoneNumber.length()>13)//超过长度，按4处理
		{
			return 4;
		}

		return 0;
	}
	/**
	 * 除index = 3和8是“-”以外，其他位置有“-”时，返回该index
	 * @param phoneNumber
	 * @return
	 */

	public static int getOneInvalidSeparatorIndex(String phoneNumber) {
		if (phoneNumber == null) {
			return -1;
		}

		for (int index = 0; index < phoneNumber.length(); index++) {
			if ((index == FIRST_SEPARATOR_POSITION) || (index == (SECOND_SEPARATOR_POSITION + 1))) {
				continue;
			}

			if (phoneNumber.charAt(index) == SEPARATOR) {
				return index;
			}
		}

		return -1;
	}
	public static String getEditInputTextWithoutSeparator(EditText edit) {
		if(edit == null) {
			return null;
		}

		return edit.getText().toString().trim().replaceAll(String.valueOf(SEPARATOR), "");
	}
	public static boolean isNull(EditText editText) {
		String text = editText.getText().toString().trim();
		if (text != null && text.length() > 0) {
			return false;
		}
		return true;
	}
	/**
	 * 设置EditText输入手机号时分隔处理，方法用在onTextChanged中
	 * @param edit
	 */
	public static void setEditInputPhoneSeparator(EditText edit) {
		if(edit == null) {
			return;
		}

		Editable phoneNumberEditable = edit.getEditableText();


		switch (parsePhoneNumber(phoneNumberEditable.toString())) {
			case 1:
				int oneInvalidSeparatorIndex = getOneInvalidSeparatorIndex(phoneNumberEditable.toString());
				phoneNumberEditable.delete(oneInvalidSeparatorIndex, oneInvalidSeparatorIndex + 1);//删除该“-”
				break;

			case 2:
				phoneNumberEditable.insert(FIRST_SEPARATOR_POSITION, String.valueOf(SEPARATOR));
				break;

			case 3:
				phoneNumberEditable.insert(SECOND_SEPARATOR_POSITION + 1, String.valueOf(SEPARATOR));
				break;

			case 4:
				phoneNumberEditable.delete(phoneNumberEditable.length() - 1, phoneNumberEditable.length());
				break;

			case -1:
			case 0:
			default:
				break;
		}
	}
}
